'use strict';
const db = uniCloud.database();
const collection = db.collection('one-daily-articles')
exports.main = async ({type}, context) => {
	// //获取已存库的最大文章ID
	let maxIdInDb = await getMaxTime();
	console.log('maxIdInDb',maxIdInDb);
	console.log(getdate());
	
	console.log( getdate()!= maxIdInDb );
	if(getdate()!= maxIdInDb){
		// 开始抓取首页链接
		var indexArr = []
		let apiUrl='http://api.tianapi.com/txapi/one/index'
		const res = await uniCloud.httpclient.request(apiUrl, {
		    method: 'GET',
		    data: {
		      key: '1a162a6b0fec66a258dc8f80a8c9cfdb',
			  date:getdate()
		    },
		    contentType: 'json', // 指定以application/json发送data内的数据
		    dataType: 'json' // 指定返回值为json格式，自动进行parse
		  })
		console.log(res.data)
		if(res.status==200 && res.data &&res.data.newslist.length>0){
			let list=res.data.newslist
			for (let i = 0; i < list.length; i++) {
				 let _time= list[i].date
				 
				 if(new Date(_time)> new Date(maxIdInDb)){
					 indexArr.unshift(list[i])
				 }
			}
			console.log('新增文章数量：',indexArr.length);
			
			if(indexArr.length>0){
				indexArr.forEach((v,i)=>{
					v.imgurl='https://images.weserv.nl/?url='+v.imgurl;
					saveArticle(v)
				})
				
			}
		}
		
		
	}else {
		console.log('不获取数据');
		return
	}
	
};
  
function getdate(num=0){
	//num=0 代表今天，1表示前一天，2表示后一天
	var time=(new Date).getTime()-24*60*60*1000*num;
	var yesterday=new Date(time);
	var month=yesterday.getMonth();
	var day=yesterday.getDate();
	yesterday=yesterday.getFullYear() + "-" + (yesterday.getMonth()>= 9 ? (yesterday.getMonth() + 1) : "0" + (yesterday.getMonth() + 1)) + "-" +(yesterday.getDate()>= 9 ? (yesterday.getDate()) : "0" + (yesterday.getDate()));
	 return yesterday
}

async function getMaxTime(){
  // 获取已存库的最大文章ID
  const record = await collection.field({
    One_id: true
  }).orderBy("One_id", "desc").limit(1).get()
	console.log(record);
  let maxIdInDb = 0
  if (record && record.data && record.data.length > 0) {
    maxIdInDb = record.data[0].One_id
  }
  return maxIdInDb
}

async function saveArticle(article) {
	// console.log(article);
	let articles = {
	  One_id: article.date,
	  ...article
	}
  
  const addRes = await collection.add(articles)
  if (addRes.id || addRes.affectedDocs === 1) {
    console.log( " -> 添加成功");
  }

}